<template>
  <el-select
    style="width: 100%"
    :value="value"
    filterable
    remote
    clearable
    reserve-keyword
    placeholder="请输入"
    :remote-method="remoteMethod"
    @clear="clearProductAction"
    @change="change($event)"
    @focus="productFocusAction">
    <el-option
      v-for="item in listOptions"
      :key="item.id"
      :label="item[labelKey]"
      :value="item[valueKey]"></el-option>
  </el-select>
</template>
<script>
  export default {
    name: 'index',
    props: {
      value: {},
      action: {
        // action名称
        type: Function,
        default: null,
      },
      labelKey: {
        type: String,
        default: "name",
      },
      valueKey: {
        type: String,
        default: "id",
      },
      defaultValue:{
        type: [String,Number],
        default: 0,
      },
      searchDefault: {
        type: Object,
        default: null,
      },
    },
    data() {
      return{
        listOptions: [],
        condition: {}
      }
    },
    watch:{
      value:{
        handler(val){
          if(val){
            this.condition[this.valueKey] = val
          }
          this.getListData()
        },
        immediate:true
      },
      searchDefault: {
        handler(val) {
          if (val) {
            this.condition = JSON.parse(JSON.stringify(val));
            this.$set(this, 'condition', this.condition);
          }
        },
        immediate: true,
      },
    },
    methods:{
      change(val) {
        this.$emit("input", val);
      },
      remoteMethod(query){
        this.condition[this.labelKey] = [ 'like', query ]
        this.getListData()
      },
      clearProductAction(){
        this.$set( this, 'listOptions', [])
      },
      productFocusAction(){
        if( this.searchDefault ){
          this.$set(this, 'condition', JSON.parse(JSON.stringify(this.searchDefault)));
        } else {
          this.$set(this, 'condition', {});
        }
        this.getListData()
      },
      getListData(){
        this.$set( this, 'listOptions', [])
        this.action({ page: 1, limit: 20, where: this.condition }).then(res=>{
          this.$set( this, 'listOptions', res.data.data )
        })
      }
    }
  };
</script>
